package com.antgroup.seckill.business.common.config;

import com.alibaba.fastjson2.JSON;
import com.antgroup.seckill.business.common.enums.RespBeanEnum;
import com.antgroup.seckill.business.common.vo.response.RespBean;
import com.antgroup.seckill.business.goods.model.User;
import com.antgroup.seckill.business.goods.service.IUserService;
import com.antgroup.seckill.business.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author wangxy
 * @date 2024/8/6 18:27
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            User user = getUserInfo(request, response);
            //放到threadLocal上下文
            UserContext.setUser(user);

            HandlerMethod hm = (HandlerMethod) handler;

            //获取方法上面自定义注解
            AccessLimit methodAnnotation = hm.getMethodAnnotation(AccessLimit.class);
            if (Objects.isNull(methodAnnotation)) {
                return true;
            }
            int second = methodAnnotation.second();
            int macConunt = methodAnnotation.maxCount();
            boolean needLogin = methodAnnotation.needLogin();
            String uri = request.getRequestURI();
            if (needLogin) {
                if (Objects.isNull(user)) {
                    renderPath(response, RespBeanEnum.ILLEGAL_LOGIN);
                    return false;
                }
                uri += ":" + user.getId();
                Integer count = (Integer) redisTemplate.opsForValue().get(uri);
                if (null == count) {
                    redisTemplate.opsForValue().set(uri, 1, second, TimeUnit.SECONDS);
                } else if (count < macConunt) {
                    redisTemplate.opsForValue().increment(uri);
                } else {
                    renderPath(response, RespBeanEnum.REQUEST_NUMBER_LIMIT);
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除 ThreadLocal 中的数据
        UserContext.clear();
    }

    /**
     * 构建返回对象
     *
     * @param response
     */
    private void renderPath(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        RespBean respBean = RespBean.error(respBeanEnum);
        out.write(JSON.toJSONString(respBean));
        out.flush();
        out.close();
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @param response
     * @return
     */
    private User getUserInfo(HttpServletRequest request, HttpServletResponse response) {

        String userCookie = CookieUtil.getCookie(request, "userCookie")
                .map(Cookie::getValue)
                .orElse(null);

        if (StringUtils.isEmpty(userCookie)) {
            return null;
        }
        return iUserService.getUserByCookie(request, response, userCookie);
    }
}
